<template>
  <!-- 补全证件 -->
    <uni-forms
        ref="ruleForm"
        :modelValue="ruleForm"
        :rules="rules"
        :label-width="(ruleForm.credentialType != 1)?'200rpx':'170rpx'" type="line" label-align="right"
        class="paddingAll">
      <view class="text-row">
        <span>根据国家监管要求，请您完善个人证件信息</span>
        <p>温馨提示：个人证件信息30天内仅允许修改2次</p>
      </view>
      <uni-forms-item label="真实姓名" name="name">
        <uni-easyinput v-model="ruleForm.name" type="text" disabled/>
      </uni-forms-item>
      <uni-forms-item label="手机号码" name="mobile">
        <uni-easyinput v-model="ruleForm.mobile" type="text" disabled/>
      </uni-forms-item>
      <uni-forms-item label="证件类型" name="credentialTypeName">
        <uni-easyinput v-model="ruleForm.credentialTypeName" type="text" disabled/>
      </uni-forms-item>
      <uni-forms-item :label="(credentialType == 1)?'身份证号码':'证件号码'" name="idNumber">
        <uni-easyinput v-model="ruleForm.idNumber" type="text" disabled/>
      </uni-forms-item>
      <uni-forms-item label="证件照片" name="idNumberPic" :required="true">
        <view class="idNumber-pic">
          <span
              v-if="userInfo.staffCertification.credentialStatus == 0"
              class="errorColor"
              style="margin-right: 15rpx;"
          >无效证件
          </span>
          <span
              v-if="userInfo.staffCertification.credentialStatus == 4"
              class="errorColor"
              style="margin-right: 15rpx;"
          >证件已过期
          </span>
          <span class="gray-text" @click="idAsk">查看证件拍摄要求</span>
        </view>
        <view style="margin-top: 15px;display: flex;">
          <!-- 身份证正面图片上传 -->
          <view style="text-align:center;" @click="toIdCardCropper(0)">
            <img :src="idCardFrontImg" alt="" class="idcard-preview">
            <view style="color: #444;font-size: 20rpx;">正面图片</view>
          </view>
          <!-- 身份证反面图片上传 -->
          <view style="text-align:center;" @click="toIdCardCropper(1)">
            <img :src="idCardBackImg" style="margin-left: 15px" alt="" class="idcard-preview">
            <view style="color: #444;font-size: 20rpx;">反面图片</view>
          </view>
        </view>
      </uni-forms-item>
      <uni-forms-item v-if="ruleForm.credentialType != 1" label="证件过期时间" name="credentialExpDate" :required="true">
        <view style="display: flex;align-items: center;">
          <uni-datetime-picker
              type="date"
              :clear-icon="false"
              style="margin-right: 5px;width: 100%;"
              v-model="ruleForm.credentialExpDate"
              :disabled="longTerm[0]"
          />
          <uni-data-checkbox multiple v-model="longTerm" :localdata="longTermArr"/>
        </view>

        <!--        <view style="display: flex;align-items: center;">-->
        <!--          <view style="width:260rpx;margin-right: 20rpx;">-->
        <!--            <uni-datetime-picker-->
        <!--                type="date"-->
        <!--                :clear-icon="false"-->
        <!--                v-model="ruleForm.credentialExpDate"-->
        <!--                :disabled="longTerm"/>-->
        <!--          </view>-->
        <!--          <checkbox-group>-->
        <!--            <label>-->
        <!--              <checkbox value="longTerm" color="#00a660" style="transform:scale(0.7)"/>-->
        <!--              长期有效-->
        <!--            </label>-->
        <!--          </checkbox-group>-->
        <!--        </view>-->
      </uni-forms-item>
      <uni-forms-item>证件信息将进行安全加密，保障信息安全。</uni-forms-item>
	  <view class="submit_btn">
	    <button size="mini" class="back-Btn" @click="cancel">取消</button>
	    <button size="mini" class="next-Btn" @click="submit">立即提交</button>
	  </view>
    </uni-forms>
</template>

<script>
import {findUserInfo} from "@/api/ec/person/user/userInfo";
import {getDicts} from "../../../../api/system/dict/data";
import config from '@/config'
import {getToken} from '@/utils/auth'
import {credentialPerfect} from "../../../../api/ec/person/certification/info";

export default {
  data() {
    return {
      // 数据字典
      dicts: {
        // 证件类型字典
        ec_person_certification_certificates_type: [],
      },
      // 长期有效
      longTermArr: [
        {text: '长期有效', value: true}
      ],
      //用户信息
      userInfo: {
        staffCertification: {},// 认证信息
      },
      // 证件类型
      credentialType: 1,
      // 表单参数
      ruleForm: {
        name: undefined,
        idNumber: undefined,
        mobile: undefined,
        credentialType: undefined,
        credentialTypeName: undefined,
        idCardFrontImg: undefined,
        idCardBackImg: undefined,
        credentialExpDate: undefined,
      },
      idCardFrontImg: undefined,
      idCardBackImg: undefined,
      // 证件是否长期有效
      longTerm: [],
      // 表单校验
      rules: {
        idNumberPic: [
          {required: true, message: "请上传证件照片", trigger: "blur"},
        ],
        credentialExpDate: [
          {required: true, message: "请选择证件过期时间", trigger: "blur"},
        ],
      },
    }
  },
  onLoad() {
    this.bindingRefreshData();
    this.getDicts();
  },
  onUnload(){
    this.unbindingRefreshData();
  },
  created() {
    this.findUserInfo();
  },
  methods: {
    /** 绑定 */
    bindingRefreshData() {
      // 证件图片剪切成功
      uni.$on('perfectInfoCropperSuccess', (base64, type) => {
        this.cropperSuccess(base64, type);
      });
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('perfectInfoCropperSuccess');
    },
    // ===============================================================================================================
    // ==== 加载数据字典
    // ===============================================================================================================
    /**加载数据字典*/
    getDicts() {
      // 加载证件类型数据字典
      getDicts("ec_person_certification_certificates_type").then(response => {
        const range = []
        response.data.forEach((dict, index) => {
          range.push({value: parseInt(dict.dictValue), text: dict.dictLabel})
        });
        this.dicts.ec_person_certification_certificates_type = range;
      });
    },
    /** 查看证件拍摄要求 */
    idAsk() {
      this.$tab.navigateTo('./idAsk')
    },
    /** 查询用户及认证信息 */
    findUserInfo() {
      this.$modal.loading();
      findUserInfo().then(response => {
        uni.hideLoading()
        this.userInfo = response.data;
        this.credentialType = this.userInfo.staffCertification.credentialType;
        // 证件图片
        this.userInfo.staffCertification.idCardFrontImg = (!!this.userInfo.staffCertification.idCardFrontImg) ? "data:image/png;base64," + this.userInfo.staffCertification.idCardFrontImg : null;
        this.userInfo.staffCertification.idCardBackImg = (!!this.userInfo.staffCertification.idCardBackImg) ? "data:image/png;base64," + this.userInfo.staffCertification.idCardBackImg : null;
        this.credentialType = this.userInfo.staffCertification.credentialType;
        // 过期时间
        let credentialExpDate;
        if (this.userInfo.staffCertification.credentialExpDate == "长期") {
          this.longTerm = [true];
          credentialExpDate = "";
        } else {
          this.longTerm = [false];
          credentialExpDate = (!!this.userInfo.staffCertification.credentialExpDate) ? this.userInfo.staffCertification.credentialExpDate : "";
        }
        this.ruleForm = {
          id: this.userInfo.staffCertification.id,
          name: this.userInfo.staffCertification.name,
          mobile: this.userInfo.staffCertification.mobile,
          idNumber: this.userInfo.staffCertification.idNumber,
          credentialType: this.userInfo.staffCertification.credentialType,
          credentialTypeName: this.getCertificatesTypeName(this.userInfo.staffCertification.credentialType),
          credentialExpDate: credentialExpDate,
        };
        this.setCropperDefaultImage();
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 获取证件类型名称 */
    getCertificatesTypeName(value) {
      let type = this.dicts.ec_person_certification_certificates_type;
      for (let i = 0; i < type.length; i++) {
        if (value == type[i].value) {
          return type[i].text;
        }
      }
    },
    /** 设置证件默认图片 */
    setCropperDefaultImage() {
      // 正面图片
      if (this.userInfo.staffCertification == undefined || this.userInfo.staffCertification.idCardFrontImg == null
          || this.userInfo.staffCertification.idCardFrontImg == '') {
        this.idCardFrontImg = (this.credentialType != 1) ? require("@/static/images/idcard-zheng.jpg") : require('@/static/images/card-people.jpg')
      } else {
        this.idCardFrontImg = this.userInfo.staffCertification.idCardFrontImg;
      }
      // 反面图片
      if (this.userInfo.staffCertification == undefined || this.userInfo.staffCertification.idCardBackImg == null
          || this.userInfo.staffCertification.idCardBackImg == '') {
        this.idCardBackImg = (this.credentialType != 1) ? require('@/static/images/idcard-fan.jpg') : require('@/static/images/card-guo.jpg')
      } else {
        this.idCardBackImg = this.userInfo.staffCertification.idCardBackImg;
      }
    },
    /** 修改证件图片 */
    toIdCardCropper(idCartType) {
      let defaultImage;
      // 0 正面；1 反面
      if (idCartType == 0) {
        defaultImage = this.idCardFrontImg;
      } else {
        defaultImage = this.idCardBackImg;
      }
      let imageSrc
      // 组装图片加载地址
      if (defaultImage.startsWith("data:image/png;base64,")) {
        imageSrc = defaultImage;
      } else {
        imageSrc = config.baseUrl + "/common/lksign-authentication?path=" + defaultImage + "&token=" + getToken();
      }
      // 跳转页面
      uni.navigateTo({url: "/pages/common/imageCropper/index?callbackMethod=perfectInfoCropperSuccess&type=" + idCartType + "&imageSrc=" + encodeURIComponent(imageSrc)});
    },
    /** 身份证剪切成功回调方法 */
    cropperSuccess(base64, type) {
      if (type == 0) {
        this.idCardFrontImg = base64;
        this.ruleForm.idCardFrontImg = base64;
      } else {
        this.idCardBackImg = base64;
        this.ruleForm.idCardBackImg = base64;
      }
    },
    /** 取消 */
    cancel() {
      uni.navigateBack({delta: 1});
    },
    /** 提交 */
    submit() {
      if (this.ruleForm.idCardFrontImg == undefined || this.ruleForm.idCardFrontImg == '') {
        return this.$modal.msgError("请上传身份证件正面图片！");
      }
      if (!this.ruleForm.idCardFrontImg.startsWith("data:image")) {
        return this.$modal.msgError("请重新上传身份证件正面图片！");
      }
      if (this.ruleForm.idCardBackImg == undefined || this.ruleForm.idCardBackImg == '') {
        return this.$modal.msgError("请上传身份证件反面图片");
      }
      if (!this.ruleForm.idCardBackImg.startsWith("data:image")) {
        return this.$modal.msgError("请重新上传身份证件反面图片！");
      }
      if (this.longTerm) {
        this.ruleForm.credentialExpDate = "长期";
      }
      this.$modal.loading();
      credentialPerfect(this.ruleForm).then(response => {
        uni.hideLoading()
        this.$modal.msgSuccess("操作成功！");
        // 返回上级页面
        uni.navigateBack(1);
        // 回调方法
        uni.$emit('refreshUserInfoData');
      }).catch(() => {
        uni.hideLoading()
      });
    },
  }
}
</script>

<style scoped lang="scss">
	::v-deep .uni-input-input {
	  color: #666666;
	  opacity: 1;
	  -webkit-opacity: 1;
	  -webkit-text-fill-color: #666666; // ios 和 安卓9.0 必须添加此属性，才会生效
	}
.text-row {
  text-align: center;
  margin-bottom: 26rpx;

  p {
    color: $uni-color-primary;
    margin: 10rpx 0;
  }
}

.idNumber-pic {
  height: 70rpx;
  line-height: 70rpx;
  display: flex;
  align-items: center;
  line-height: 20rpx;

  .gray-text {
    font-size: 24rpx;
    color: $uni-color-primary;
    cursor: pointer;
  }
}

.idcard-preview {
  position: relative;
  display: inline-block;
  width: 228rpx;
  height: 144rpx;
}

.submit_btn {
  margin: 80rpx 50rpx 0 50rpx;
  display: flex;
  justify-content: space-around;

  button {
    width: 42%;
    font-size: 28rpx;
  }

  .next-Btn {
    background-color: $uni-color-primary;
	border: solid 1rpx $uni-color-primary;
    border-radius: 10rpx;
    color: #fff;
  }

  .back-Btn {
    border-radius: 10rpx;
    border: solid 1rpx $uni-color-primary;
    color: $uni-color-primary;
    background: #fff;
  }

}

::v-deep .uni-forms-item {
  margin-bottom: 38rpx;
}

.paddingAll {
  padding: 30rpx 40rpx 20rpx;
}

page {
  background: $uni-bg-color;
}
</style>
